package com.hg.admin.db.dao;

import java.util.ArrayList;
import java.util.List;

import org.jdiy.core.Args;
import org.jdiy.core.Ls;
import org.jdiy.core.Rs;

import com.hg.admin.db.dto.AdminDTO;
import com.hg.admin.vo.VO4admin;
import com.hg.util.db.IDao;


public class AdminDAO extends IDao {
	String table =db_prefix+"admin";
	
	public AdminDTO loginDao(VO4admin admin){
		AdminDTO dto=null;
		String username=admin.getUsername();
		String password=admin.getPassword();	
		Args args = new Args(table,"adm_name='"+username+"' and adm_password='"+password+"'");
		
		Rs rs=dao.rs(args);
		if(!rs.isNull()){
			String adm_name=rs.getString("adm_name");
			int id=rs.getInt("id");
			dto = new AdminDTO();
			dto.setId(id+"");
			dto.setUsername(adm_name);
		}
		return dto;
		
	}
	
	public List<AdminDTO> findAllAdmin(){
		List<AdminDTO> list = null;
		try{
			Ls ls = dao.ls(new Args(table));
			list = new ArrayList<AdminDTO>();
			for(Rs rs:ls.getItems()){
				AdminDTO dto = new AdminDTO();
				dto.setId(rs.get("admin_id"));
				dto.setUsername(rs.get("username"));
				dto.setPassword(rs.get("password"));
				list.add(dto);
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return list;
	}

	public boolean passwordUpdate(String id, String oldpass, String newpass) {
		try{
			
			
			Rs rs = dao.rs(new Args(table,"admin_id="+id+" and password='"+oldpass+"'"));
			if(rs.isNull()){
				return false;
			}else{
				rs.set("password", newpass);
				dao.save(rs);
				return true;
			}
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	
	public AdminDTO findAdmin(String username){
		AdminDTO dto=null;	
		Args args = new Args(table," adm_name='"+username+"'");
		
		Rs rs=dao.rs(args);
		if(!rs.isNull()){
			String adm_name=rs.getString("adm_name");
			int id=rs.getInt("id");
			dto = new AdminDTO();
			dto.setId(id+"");
			dto.setUsername(adm_name);
			dto.setPassword(rs.getString("adm_password"));
			dto.setAdmin_role_id(rs.getInt("admin_role_id"));
		}
		return dto;
		
	}
	
	public boolean checkAdmin(String id,String adm_name){
		Args args = new Args(table,"id='"+id+"' and adm_name='"+adm_name+"'");
		Rs rs=dao.rs(args);
		if(rs.isNull()){
			return false;
		}else{
			return true;
		}
	}
	
	/****************************************管理员移动端**************************************/
	public AdminDTO encapsulation(Rs rs){
		AdminDTO dto = new AdminDTO();
		dto.setId(rs.get("id"));
		dto.setPassword(rs.get("adm_password"));
		dto.setUsername(rs.get("adm_name"));
		return dto;
	}
	
	/**
	 * 根据用户ID获取绑定的管理员
	 * @param user_id
	 * @return
	 */
	public AdminDTO getRowByUserId(String user_id){
		AdminDTO dto=null;
		Args args = new Args(table,"role_id='"+user_id+"'");
		Rs rs=dao.rs(args);
		if(!rs.isNull()){
			dto = this.encapsulation(rs);
		}
		return dto;
	}
}
